var timeInteval // 通知定时器
var goal // 每日目标
var cup // 杯子大小
var haveDrink // 当天已喝
var date // 最后时间 喝水时记录 用于第二天清零
var duration // 通知间隔 minute
var alerting // 是否通知
var colorFront // 波浪前
var colorBehind // 波浪后
var bgColor // 背景色
var settingThemeColor // 设置主题色


chrome.runtime.onInstalled.addListener(() => {
		chrome.storage.local.clear(function() {
			console.log('remove all ');
			reset()
	  });
});
checkAlert()

function checkAlert(){
	chrome.storage.sync.get(null,res=>{
		let duration = res.duration
		let alerting = res.alerting
		if(alerting){
			console.log("重新开始提醒")
			setAlert(true)
		}
	})
}


function reset(){
	console.log('reset')
	chrome.storage.sync.set({goal: 1500});
	chrome.storage.sync.set({cup: 300});
	chrome.storage.sync.set({haveDrink: 0});
	chrome.storage.sync.set({date: new Date().getTime()});
	chrome.storage.sync.set({colorFront: '#32BAFA'});
	chrome.storage.sync.set({colorBehind: '#2C7FBE'});
	chrome.storage.sync.set({bgColor: '#1e384c'});
	chrome.storage.sync.set({duration: 60});
	chrome.storage.sync.set({alerting: false});
	chrome.storage.sync.set({settingThemeColor: '#1e384c'});
	clearInterval(timeInteval)
}



// 设置通知
function setAlert(bool){
	if(bool){
		chrome.storage.sync.set({alerting: true});
		clearInterval(timeInteval)
		console.log("开始通知")
		chrome.storage.sync.get(null,res=>{
			timeInteval = setInterval(()=>{
				notify()
			}, res.duration * 60 * 1000)			
		})

	}
	else{
		clearInterval(timeInteval)
		chrome.storage.sync.set({alerting: false});
	}
}

function notify(){
	  // 先检查浏览器是否支持
	  if (!("Notification" in window)) {
	    alert("您的浏览器不支持向您发送通知");
			chrome.storage.sync.set({alerting: false});
	  }
	
	  // 检查用户是否同意接受通知
	  else if (Notification.permission === "granted") {
	    var notification = new Notification("休息一下，喝口水吧!");
	  }
	
	  // 否则我们需要向用户获取权限
	  else if (Notification.permission !== "denied") {
	    Notification.requestPermission().then(function (permission) {
	      if (permission === "granted") {
	         var notification = new Notification("休息一下，喝口水吧!");
	      }
	    });
	  }
		else{
			chrome.storage.sync.set({alerting: false});
		}
}